package com.jdls.tanhua.server;

import cn.hutool.core.collection.CollUtil;
import com.jdls.tanhua.dubbo.*;
import com.jdls.tanhua.exception.AllException;
import com.jdls.tanhua.interceptor.UserHolder;
import com.jdls.tanhua.mongo.RecommendUser;
import com.jdls.tanhua.mongo.UserLike;
import com.jdls.tanhua.mongo.Visitors;
import com.jdls.tanhua.pojo.*;
import com.jdls.tanhua.template.AipTemplate;
import com.jdls.tanhua.template.OssTemplate;
import com.jdls.tanhua.template.SmsTemplate;
import com.jdls.tanhua.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.omg.CORBA.TIMEOUT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author 嘉德罗斯
 * @date 2021/10/23
 */
@Service
public class UserInfoServer {

    private final String TH = "tanhua";
    @DubboReference(timeout = 400000)
    private UserInfoApi userInfoApi;

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private UserApi userApi;

    @DubboReference(timeout = 30000)
    private BlackListApi blackListApi;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipTemplate aipTemplate;


    public void save(UserInfo userInfo) {
        String birthday = userInfo.getBirthday();
        long date = System.currentTimeMillis();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = simpleDateFormat.parse(birthday);
        } catch (ParseException e) {
        }
        long time = parse.getTime();
        Long a = date - time;
        long l = a / (365 * 24 * 60 * 60 * 1000L);
        userInfo.setAge(String.valueOf(l));
        userInfoApi.save(userInfo);
    }

    //修改头像
    public void update(Integer id, MultipartFile headPhoto) throws IOException {
        String oss = "https://" + ossTemplate.oss(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        System.out.println(oss);
        boolean aip = aipTemplate.aip("https://0jdls0.oss-cn-guangzhou.aliyuncs.com/2021/10/23/94f82899-802d-42b7-81a5-115a4b6d7912.png");
        //boolean aip = aipTemplate.aip(oss);
        if (!aip) {
            throw new AllException(ErrorResult.faceErr());
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(Long.valueOf(id));
        userInfo.setAvatar(oss);
        userInfoApi.update(userInfo);
    }

    //查看自己资料
    public UserInfo find(Long id) {
        UserInfo userInfo = userInfoApi.find(id);
        return userInfo;
    }

    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }


    public SettingsVo settings(Long id, String phone) {
        SettingsVo vo = new SettingsVo();
        vo.setId(id);
        vo.setPhone(phone);
        Question question = questionApi.find(id);


        if (question == null) {
            vo.setStrangerQuestion("你好");
        } else {
            vo.setStrangerQuestion(question.getTxt());
        }

        Settings settings = settingsApi.find(id);

        if (settings == null) {
            vo.setPinglunNotification(true);
            vo.setGonggaoNotification(true);
            vo.setLikeNotification(true);
        } else {
            vo.setPinglunNotification(settings.getPinglunNotification());
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setLikeNotification(settings.getLikeNotification());
        }

        return vo;
    }

    public void questions(Long userId, String content) {
        Question question = questionApi.find(userId);
        if (question == null) {
            Question qu = new Question();
            qu.setUserId(userId);
            qu.setTxt(content);
            questionApi.save(qu);
            return;
        }
        question.setTxt(content);
        questionApi.update(question);
        return;

    }

    public void setting(Map map, Long userId) {
        Boolean likeNotification = (Boolean) map.get("likeNotification");
        Boolean pinglunNotification = (Boolean) map.get("pinglunNotification");
        Boolean gonggaoNotification = (Boolean) map.get("gonggaoNotification");

        Settings settings = settingsApi.find(userId);
        if (settings == null) {
            settings = new Settings();
            settings.setUserId(userId);
            settings.setGonggaoNotification(gonggaoNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setLikeNotification(likeNotification);
            settingsApi.save(settings);
            return;
        }
        settings.setGonggaoNotification(gonggaoNotification);
        settings.setPinglunNotification(pinglunNotification);
        settings.setLikeNotification(likeNotification);
        settingsApi.update(settings);
        return;
    }

    public PageResult blacklist(int page, int pageSize) {
        Long userId = UserHolder.getUserId();
        PageResult pageResult = blackListApi.findAll(userId, page, pageSize);
        List<Long> ids = (List<Long>) pageResult.getItems();

        List<UserInfo> list = userInfoApi.findAll(ids);
        pageResult.setItems(list);
        return pageResult;
    }


    public void delete(Long id) {
        Long userId = UserHolder.getUserId();
        blackListApi.delete(userId, id);
    }

    public void sendCode() {
        String phone = UserHolder.getPhone();
        String code = "111111";
        //smsTemplate.sendSms(phone,code);
        redisTemplate.opsForValue().set(TH + phone, code, 5L, TimeUnit.MINUTES);
    }

    public Map code(String code) {
        String phone = UserHolder.getPhone();
        String s = redisTemplate.opsForValue().get(TH + phone);
        if (s == null) {
            throw new AllException(ErrorResult.codeTimeout());
        } else if (!(code.equals(s))) {
            throw new AllException(ErrorResult.codeErr());
        }

        Map<String, Boolean> map = new HashMap();
        map.put("verification", true);
        return map;

    }

    public void update(String phone) {
        User user = userApi.findPhone(phone);
        if (user != null) {
            throw new AllException(ErrorResult.phoneErr());
        }

        Long userId = UserHolder.getUserId();
        user = new User();
        user.setId(userId);
        user.setMobile(phone);
        userApi.update(user);
    }

    //查看喜欢,互相喜欢,粉丝数量
    public CountsVo counts() {
        Long userId = UserHolder.getUserId();
        Map<String, Integer> counts = userLikeApi.findCounts(userId);

        CountsVo countsVo = new CountsVo();
        //设置互相喜欢数量
        countsVo.setEachLoveCount(counts.get("eachLoveCount"));
        //设置我喜欢数量
        countsVo.setLoveCount(counts.get("loveCount"));
        //设置我的粉丝数量
        countsVo.setFanCount(counts.get("fanCount"));
        return countsVo;

    }

    //互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
    public PageResult friends(Integer type, int page, int pageSize, String nickname) {
        //当前登陆人的id
        Long userId = UserHolder.getUserId();
        //获取的id集合
        List<Long> ids = new ArrayList<>();
        //vo返回值
        List<VisitorsVo> list;
        //获取我关注的用户集合
        List<UserLike> userLikes;

        if (type == 1) {
            //1 互相关注
            //获取我关注的用户集合
            userLikes = userLikeApi.like(userId, page, pageSize);
            //获取我粉丝的用户集合

            List<UserLike> fanLike = userLikeApi.fan(userId, page, pageSize);
            for (UserLike userLike : userLikes) {
                for (UserLike like : fanLike) {
                    if (userLike.getLikeUserId() == like.getUserId()) {
                        ids.add(userLike.getLikeUserId());
                    }
                }
            }

            //根据id集合去userInfo表查询用户信息
            List<UserInfo> userInfos = userInfoApi.findAll(ids);
            //查询推荐用户表,获取缘分值
            List<RecommendUser> recommendUsers = recommendUserApi.findAll(userId, ids);
            list = new ArrayList<>();
                for (UserInfo userInfo : userInfos) {
                            VisitorsVo init = VisitorsVo.init(userInfo);
                            init.setAlreadyLove(true);
                            if (recommendUsers != null) {
                                for (RecommendUser recommendUser : recommendUsers) {
                                    if (recommendUser.getUserId() == userInfo.getId()) {
                                        String score = recommendUser.getScore().toString();
                                        int i = score.indexOf(".");
                                        score = score.substring(0, i);
                                        init.setMatchRate(Integer.valueOf(score));
                                    }
                                }
                            }
                            list.add(init);
                        }
        } else if (type == 2) {
            //2 我关注
            //获取我关注的用户集合
            userLikes = userLikeApi.like(userId, page, pageSize);
            //获取这些用户的id集合
            ids = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
            //根据id集合去userInfo表查询用户信息
            List<UserInfo> userInfos = userInfoApi.findAll(ids);
            //查询推荐用户表,获取缘分值
            List<RecommendUser> recommendUsers = recommendUserApi.findAll(userId, ids);
            list = new ArrayList<>();
            for (UserLike userLike : userLikes) {
                for (UserInfo userInfo : userInfos) {
                    if (userLike.getLikeUserId() == userInfo.getId()) {
                        VisitorsVo init = VisitorsVo.init(userInfo);
                        init.setAlreadyLove(userLike.getIsLike());
                        if (recommendUsers != null) {
                            for (RecommendUser recommendUser : recommendUsers) {
                                if (recommendUser.getUserId() == userInfo.getId()) {
                                    String score = recommendUser.getScore().toString();
                                    int i = score.indexOf(".");
                                    score = score.substring(0, i);
                                    init.setMatchRate(Integer.valueOf(score));
                                }
                            }
                        }
                        list.add(init);
                    }
                }
            }
        } else if (type == 3) {
            //3 粉丝
            //获取我粉丝的用户集合
            userLikes = userLikeApi.fan(userId, page, pageSize);
            ids = CollUtil.getFieldValues(userLikes, "userId", Long.class);
            //根据id集合去userInfo表查询用户信息
            List<UserInfo> userInfos = userInfoApi.findAll(ids);
            //查询推荐用户表,获取缘分值
            List<RecommendUser> recommendUsers = recommendUserApi.findAll(userId, ids);
            list = new ArrayList<>();
            for (UserLike userLike : userLikes) {
                for (UserInfo userInfo : userInfos) {
                    if (userLike.getUserId() == userInfo.getId()) {
                        VisitorsVo init = VisitorsVo.init(userInfo);
                        init.setAlreadyLove(userLike.getIsLike());
                        if (recommendUsers != null) {
                            for (RecommendUser recommendUser : recommendUsers) {
                                if (recommendUser.getUserId() == userInfo.getId()) {
                                    String score = recommendUser.getScore().toString();
                                    int i = score.indexOf(".");
                                    score = score.substring(0, i);
                                    init.setMatchRate(Integer.valueOf(score));
                                }
                            }
                        }
                        list.add(init);
                    }
                }
            }
        } else {
            //4 谁看过我
            String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String key = "visitors" + format;
            String hashKey = userId.toString();
            //把当前时间设置进redis
            long time = new Date().getTime();
            redisTemplate.opsForHash().put(key, hashKey, time + "");
            //设置key的过期时间为一天
            redisTemplate.expire(key, 1L, TimeUnit.DAYS);
            //获取谁看过我用户集合
            List<Visitors> visitors = visitorsApi.findById(userId, page, pageSize);
            //获取看过我的用户id
            ids = CollUtil.getFieldValues(visitors, "visitorUserId", Long.class);
            //根据id集合去userInfo表查询用户信息
            List<UserInfo> userInfos = userInfoApi.findAll(ids);
            //查询当前用户是否被我喜欢
            userLikes = userLikeApi.findIsLike(userId, ids);
            list = new ArrayList<>();
            for (Visitors visitor : visitors) {
                for (UserInfo userInfo : userInfos) {
                    if (visitor.getVisitorUserId() == userInfo.getId()) {
                        VisitorsVo init = VisitorsVo.init(userInfo);
                        String score = visitor.getScore().toString();
                        int i = score.indexOf(".");
                        score = score.substring(0, i);
                        init.setMatchRate(Integer.valueOf(score));
                        for (UserLike userLike : userLikes) {
                            if (userInfo.getId() == userLike.getLikeUserId()) {
                                init.setAlreadyLove(true);
                            }
                        }
                        list.add(init);
                    }
                }
            }
            PageResult pageResult = new PageResult(page, pageSize, list.size(), list);
            return pageResult;
        }

        PageResult pageResult = new PageResult(page, pageSize, list.size(), list);
        return pageResult;
    }
}
